/*jslint vars: true, forin: true, sloppy: true */
/*global DialogInstance, ocDialog, angular */
ocDialog.directive('ocFile', function ($filter) {
	var dateFilter = $filter('date');

	function ocFilePreLink(scope, element, attr) {
		// The DI of this oc-file dialog.
		var DI = new DialogInstance(element, scope);

		scope.mapName = scope.mapName || 'name';
		scope.mapUpdatetime = scope.mapUpdatetime || 'updateTime';
		scope.data = scope.data || [];
		scope.toolbar = scope.toolbar || [];
		scope.actionFn = scope.actionFn || angular.noop;
		scope.fileName = '';

		// Build list control object to ocList.
		scope.R = true;
		scope.CUR = -1;

		scope.selectFn = function (data) {
			scope.fileName = data[scope.mapName];
		};

		scope.action = function (event) {
			scope.actionFn.call(DI, scope);
		};

		scope.agent = function (buttonFn) {
			(buttonFn || angular.noop).call(DI, scope);
		};

		// init
		scope.$watchCollection('data', function () {
			scope.listDataRaw = []; // use to filter
			angular.forEach(scope.data, function (row, index) {
				this.push({
					index: index,
					name: row[scope.mapName],
					updateTime: dateFilter(row[scope.mapUpdatetime], 'yyyy-MM-dd')
				});
			}, scope.listDataRaw);
			scope.listData = scope.listDataRaw;
		});

		scope.$watch('fileFilter', function (newValue) {
			scope.listData = $filter('filter')(scope.listDataRaw, {name: newValue});
		});

	}

	return {
		restrict: 'E',
		transclude: true,
		replace: true,
		template:
			'<div class="oc-file" oc-draggable>' +
				'<header oc-draggable-handle><label>{{title}}</label></header>' +
				'<nav><button class="danger close" oc-dialog-close></button></nav>' +
				'<section><nav class="oc-toolbar">' +
					'<button class="ico" ng-repeat="b in toolbar"' +
						'ng-click="agent(b.fn)" ng-class="b.icon"></button>' +
					'<input ng-model="fileFilter" class="filter"/></nav>' +
					'<oc-list oc-list-data="listData"' +
						'oc-list-selected="CUR"' +
						'oc-list-select="selectFn"' +
						'oc-list-refresh="R">' +
							'<field key="name" title="名称" width="365"></field>' +
							'<field key="updateTime" title="修改日期" width="90"></field>' +
						'</oc-list>' +
					'<input ng-model="fileName" class="fileName" />' +
					'<button ng-click="action($event)" class="fn">{{actionName}}</button>' +
				'</section></div>',
		compile: function () {
			return {
				pre: ocFilePreLink
			};
		}
	};
});
